import React, { useEffect, useState } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Spin } from '@nbase/ui';
import { useAuthStore } from '~/stores/auth.store';
import { useRouteStore } from '~/stores/route.store';

/**
 * 认证路由组件
 *
 * 功能：
 * 1. 检查用户是否已登录
 * 2. 未登录用户重定向到登录页
 * 3. 应用启动时验证 token 有效性
 */
interface AuthRouteProps {
  children: React.ReactNode;
}

const AuthRoute: React.FC<AuthRouteProps> = ({ children }) => {
  const location = useLocation();
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
  const initialize = useAuthStore((state) => state.initialize);
  const loadMenus = useRouteStore((state) => state.loadMenus);
  const [isInitializing, setIsInitializing] = useState(true);

  /**
   * 应用启动时初始化认证状态和加载菜单
   * 权限已在 initialize() 中从 storage 恢复，无需额外加载
   */
  useEffect(() => {
    const initAuth = async () => {
      try {
        await initialize();
        // 认证成功后加载用户菜单（权限已在 initialize 中恢复）
        if (useAuthStore.getState().isAuthenticated) {
          await loadMenus();
        }
      } catch (error) {
        console.error('认证初始化失败:', error);
      } finally {
        setIsInitializing(false);
      }
    };

    initAuth();
  }, [initialize, loadMenus]);

  // 初始化中，显示加载状态
  if (isInitializing) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh'
      }}>
        <Spin size="large" tip="加载中...">
          <div style={{ height: '100px' }} />
        </Spin>
      </div>
    );
  }

  // 未登录，重定向到登录页
  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children as React.ReactElement;
};

export default AuthRoute;

